import 'package:flutter/material.dart';
import 'package:flutter_assist/ui/base/base_view_model.dart';
import 'package:easy_refresh/easy_refresh.dart';

abstract class ZBaseViewModelRefresh<T> extends ZBaseViewModel {
  T? data;

  late EasyRefreshController _refreshController;

  EasyRefreshController get refreshController => _refreshController;

  @override
  void initState() {
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    if (autoLoadData) refresh();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  void _setData(T data, {bool loadData = true}) {
    _refreshController.finishRefresh(IndicatorResult.success);
    this.data = data;
    setIdle();
  }

  void loadData({
    ValueChanged<T>? onSuccess,
    ValueChanged<T>? onCache,
    ValueChanged<String>? onError,
  });

  void refresh({
    ValueChanged<T>? onSuccess,
    ValueChanged<T>? onCache,
    ValueChanged<String>? onError,
  }) async {
    setBusy();
    try {
      loadData(
        onSuccess: (data) {
          _setData(data);
          if (null != onSuccess) onSuccess(data);
        },
        onCache: (data) {
          if (null != onCache) {
            _setData(data, loadData: false);
            onCache(data);
          }
        },
        onError: (data) {
          setIdle();
          if (null != onError) onError(data);
        },
      );
    } catch (e) {
      setIdle();
    }
  }
}
